package org.smallreunion.controller.authntication;

import org.slim3.controller.Navigation;
import org.slim3.util.AppEngineUtil;
import org.smallreunion.controller.AbstractController;
import org.smallreunion.service.SessionService;
import org.smallreunion.twitter.Twitter4sr;
import org.smallreunion.twitter.Twitter4srFactory;

import twitter4j.auth.RequestToken;

/**
 * AuthnticationLoginController
 *
 * @author Sinmetal
 *
 */
public class LoginController extends AbstractController {

    private SessionService sessionService = new SessionService();

    /**
     * TwitterAuthorizationURLへredirect
     */
    @Override
    public Navigation run() throws Exception {
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL
            .replace(index, callbackURL.length(), "")
            .append("/callback");

        if (!AppEngineUtil.isServer() || AppEngineUtil.isDevelopment()) {
            return redirect(callbackURL.toString());
        }

        Twitter4sr twitter = new Twitter4srFactory().getInstance();
        RequestToken requestToken =
            twitter.getOAuthRequestToken(callbackURL.toString());

        saveRequestToken(requestToken);
        response.sendRedirect(requestToken.getAuthorizationURL());
        return null;
    }

    /**
     * RequestTokenを保存
     *
     * @param requestToken
     */
    private void saveRequestToken(RequestToken requestToken) {
        String token = sessionService.putRequestToken(requestToken);
        setSessionToken(token);
    }
}
